package com.b2b.controller;

import com.alibaba.fastjson.JSON;
import com.b2b.exception.CustomException;
import com.b2b.exception.CustomUnauthorizedException;
import com.b2b.model.BiddingRecordDto;
import com.b2b.model.CollectionDto;
import com.b2b.model.ShopDto;
import com.b2b.model.entity.Shop;
import com.b2b.model.entity.goods.Stock;
import com.b2b.model.receive.BriefGood;
import com.b2b.model.receive.Good;
import com.b2b.model.receive.GoodsCondition;
import com.b2b.model.receive.GoodsList;
import com.b2b.model.GoodsDto;
import com.b2b.model.common.ResponseBean;

import com.b2b.model.entity.goods.Goods;
import com.b2b.service.ShopService;
import com.b2b.service.goodsService.GoodsService;
import com.b2b.util.GoodsUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpStatus;

import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/goods")
@PropertySource("classpath:config.properties")
public class GoodsController {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    @Value("${refreshTokenExpireTime}")
    private String refreshTokenExpireTime;

    private final GoodsUtil goodsUtil;

    private final ShopService shopService;

    private final GoodsService goodsService;

    @Autowired
    public GoodsController(GoodsService goodsService, ShopService shopService, GoodsUtil goodsUtil) {
        this.goodsUtil = goodsUtil;
        this.shopService = shopService;
        this.goodsService = goodsService;
    }

    @PostMapping("/add")
    public ResponseBean add(@RequestBody GoodsDto goodsDto) throws IOException {
        // 检查非空

        goodsUtil.insertAll(goodsDto);
        return new ResponseBean(HttpStatus.OK.value(), "新增成功(Insert Success)", null);
    }

    @DeleteMapping("/delete")
    public ResponseBean delete(Good good) throws IOException {
        Integer goodsId = good.getGoodsId();
        if (goodsId != null) {
            if (goodsUtil.hasGoods(goodsId)) {
                goodsUtil.deleteAll(goodsId);
            } else {
                return new ResponseBean(400, "商品不存在", null);
            }
        } else {
            return new ResponseBean(400, "请选择要删除的商品", null);
        }
        return new ResponseBean(HttpStatus.OK.value(), "删除成功(Delete Success)", null);
    }

    @PutMapping("/updateInfo")
    public ResponseBean updateInfo(@RequestBody GoodsDto goodsDto) throws IOException {
        // 检查非空
        goodsUtil.updateInfo(goodsDto);
        return new ResponseBean(HttpStatus.OK.value(), "修改成功(Update Success)", null);
    }

    @PutMapping("/updateStock")
//    public ResponseBean updateStock(@RequestBody Map<String,Object> stockMap) {
//
//        goodsUtil.updateStockList(stockMap);
//        return new ResponseBean(HttpStatus.OK.value(), "修改成功(Update Success)", null);
//    }
    public ResponseBean updateStock(@RequestBody List<Stock> stockMap) {
        goodsUtil.updateStockList(stockMap);
        return new ResponseBean(HttpStatus.OK.value(), "修改成功(Update Success)", null);
    }

    @PutMapping("/updateState")
    public ResponseBean updateState(@RequestBody Goods goods) throws IOException {
        goodsUtil.updateState(goods);
        return new ResponseBean(HttpStatus.OK.value(), "修改成功(Update Success)", null);
    }

    @GetMapping("/getRecommend")
    public ResponseBean getRecommend() throws IOException {
        PageHelper.startPage(1, 10);
        PageHelper.orderBy("sold_times" + " " + "desc");
        List<GoodsList> goodsList = goodsUtil.getBriefGoodsList();
//        for (int i = 0; i < goodsList.size(); i++) {
//            GetRequest getRequest = new GetRequest("goods", String.valueOf(goodsList.get(i).getGoodsId()));
//            GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
//            Map<String,Object> good = getResponse.getSourceAsMap();
//            goodsList.get(i).setMinimum(Double.parseDouble(good.get("minimum").toString()));
//        }
        PageInfo<GoodsList> selectPage = new PageInfo<GoodsList>(goodsList);
//        System.out.println(System.currentTimeMillis());

        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Select Success)", selectPage.getList());
    }
    //
    @GetMapping("/getMy")
    public ResponseBean getMy(@RequestParam Map<String, Object> map) throws IOException {
        int page = 1, rows = 10;
        if(map.containsKey("page"))
            page = Integer.parseInt(map.get("page").toString());
        if(map.containsKey("rows"))
            rows = Integer.parseInt(map.get("rows").toString());

        Character state = null;

        if(map.containsKey("state") && !map.get("state").equals("")) {
            state = map.get("state").toString().charAt(0);
        }
        PageHelper.startPage(page, rows);
        List<GoodsList> goodsList = new ArrayList<>();
        if(map.containsKey("companyId") && !map.get("companyId").equals("")){
            ShopDto shop = new ShopDto();
            shop.setCompanyId(Integer.parseInt(map.get("companyId").toString()));
            List<ShopDto> shopList = shopService.select(shop);
            Goods goods = new Goods();
            goods.setState(state);
            for (ShopDto s: shopList
                 ) {
                goods.setShopId(s.getShopId());
                List<Goods> goodsList1 = goodsService.select(goods);
                for (Goods g: goodsList1
                     ) {
                    goodsList.add(goodsUtil.selectGoods(g.getGoodsId(), 0.0));
                }
            }

        }else if (map.containsKey("shopId") && !map.get("shopId").equals("")) {
            Integer shopId = Integer.parseInt(map.get("shopId").toString());
            Goods goods = new Goods();
            goods.setState(state);
            goods.setShopId(shopId);
            List<Goods> goodsList1 = goodsService.select(goods);
            for (Goods g: goodsList1
                 ) {
                goodsList.add(goodsUtil.selectGoods(g.getGoodsId(), 0.0));
            }
        }else {
            return new ResponseBean(HttpStatus.FORBIDDEN.value(), "条件不完整", null);
        }
        PageInfo<GoodsList> selectPage = new PageInfo<>(goodsList);
        Map<String, Object> result = new HashMap<>();
        result.put("count", selectPage.getTotal());
        result.put("goodsList", selectPage.getList());
        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }

    @GetMapping("/getDetail")
    public ResponseBean getDetail(@RequestParam Map<String, String> map) {
        //检查非空
        if (!map.containsKey("goodsId")&&!map.containsKey("stockId")){
            throw new CustomException("参数缺失");
        }
//        if (map.containsKey("companyId")){
//            throw new CustomException("参数缺失");
//        }
        Integer count = null;
        if (!map.containsKey("stockId")){
            count = Integer.parseInt(map.get("goodsId").toString());
        }else {
            Integer stockId = Integer.parseInt(map.get("stockId"));
            BriefGood briefGood = goodsUtil.getBriefGoodByS(stockId);
            count = briefGood.getGoodsId();
//        Integer companyId = Integer.parseInt(map.get("companyId"));
//        return new ResponseBean(HttpStatus.OK.value(), "查询成功", goodsUtil.getDetail(goodsId, companyId));
        }
        return new ResponseBean(HttpStatus.OK.value(), "查询成功", goodsUtil.getDetail(count));
    }

    @GetMapping("/search")
    public ResponseBean getByCondition(GoodsCondition goodsCondition) throws IOException{
        SearchRequest searchRequest = new SearchRequest("goods");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.from(goodsCondition.getPage());
        sourceBuilder.size(goodsCondition.getRows());
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (!goodsCondition.getKeyWord().equals("")){
            boolQueryBuilder.should(QueryBuilders.matchPhraseQuery("goodsName", goodsCondition.getKeyWord()));
            boolQueryBuilder.should(QueryBuilders.matchPhraseQuery("categoryName", goodsCondition.getKeyWord()));
            boolQueryBuilder.should(QueryBuilders.matchPhraseQuery("modelName", goodsCondition.getKeyWord()));
            boolQueryBuilder.should(QueryBuilders.matchPhraseQuery("attribute", goodsCondition.getKeyWord()));
        }

        Good good = new Good();
        good.setGoodsName(goodsCondition.getKeyWord());
        good.setCategoryName(goodsCondition.getKeyWord());
        good.setModelName(goodsCondition.getKeyWord());
        good.setAttribute(goodsCondition.getKeyWord());
        IndexRequest request = new IndexRequest("goods");
//        Integer id = shopDto.getShopId();
        request.timeout(TimeValue.timeValueSeconds(3));
//        request.id(""+id);
        //数据封入请求
        IndexRequest source = request.source(JSON.toJSONString(good), XContentType.JSON);
        //客户端发送请求  获取响应结果
        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        String id = indexResponse.getId();

        if (null != goodsCondition.getHighest()){
            boolQueryBuilder.should(QueryBuilders.rangeQuery("highest").lte(goodsCondition.getHighest()));
        }
        if (null != goodsCondition.getMinimum()){
            boolQueryBuilder.should(QueryBuilders.rangeQuery("minimum").gt(goodsCondition.getMinimum()));
        }
        if (null != goodsCondition.getCategoryId()){
            boolQueryBuilder.must(QueryBuilders.termQuery("categoryId",goodsCondition.getCategoryId()));
        }
        sourceBuilder.query(boolQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchRequest.source(sourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);

        CountRequest countRequest = new CountRequest();
        countRequest.query(boolQueryBuilder);
        CountResponse countResponse = client.count(countRequest,RequestOptions.DEFAULT);
        long total = countResponse.getCount();

        List<Integer> goodsId = new ArrayList<Integer>();
        List<Double> minimumList = new ArrayList<Double>();
        for (SearchHit documentFields : search.getHits().getHits()) {
            Map<String,Object> result = documentFields.getSourceAsMap();
            if (result.get("goodsId")==null){
                continue;
            }
            Integer goodId = Integer.parseInt(String.valueOf(result.get("goodsId")));
            goodsId.add(goodId);
            Double minimum = Double.parseDouble(String.valueOf(result.get("minimum")));
            minimumList.add(minimum);
        }
        List<GoodsList> goodsLists = new ArrayList<GoodsList>();
        for (int i = 0; i < goodsId.size(); i++) {
            GoodsList goodsList = goodsUtil.selectGoods(goodsId.get(i), minimumList.get(i));
            goodsLists.add(goodsList);
        }
        Map<String,Object> result = new HashMap<>();
        result.put("goodsList",goodsLists);
        result.put("count",total-1);

        DeleteRequest deleteRequest = new DeleteRequest("goods", id);
        deleteRequest.timeout("1s");
        client.delete(deleteRequest, RequestOptions.DEFAULT);

        return new ResponseBean(HttpStatus.OK.value(), "查询成功(Query was successful)", result);
    }
}
